<template>
  <el-card>
    <el-button type="primary" @click="showDialogByAdd">添加品牌</el-button>
    <el-table :data="trademarkList" border style="width: 100%; margin: 20px 0">
      <el-table-column type="index" align="center" label="序号" width="60" />
      <el-table-column prop="tmName" align="center" label="品牌名称" width="150" />
      <el-table-column prop="address" label="品牌LOGO">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" :alt="row.tmName" style="width: 100px">
        </template>
      </el-table-column>
      <el-table-column prop="address" label="操作">
        <template v-slot="{row}">
          <el-button type="warning" @click="EditTrademark(row.id)">修改</el-button>
          <el-button type="danger" @click="DelOneTrademark(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="currentPage" :page-sizes="[3, 5, 10, 20]" :page-size="limit" align="center" layout="prev, pager, next, jumper, -> , total, sizes" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />

    <!-- 添加品牌 -->
    <el-dialog
      title="添加品牌"
      :visible.sync="dialogVisible"
    >
      <el-form ref="tmForm" :rules="rules" :model="tmForm" label-width="80px">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="tmForm.tmName" style="width: 400px" />
        </el-form-item>
        <el-form-item
          label="活动名称"
          prop="logoUrl"
        >
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            accept=".jpg,.jpeg,.gif"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateOneTradeMark">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import { reqGetTrademarkList, reqAddOneTrademark, reqDelOneTrademark, reqEditOneTrademark, reqUpdateOneTrademark } from '@/api/product/trademark'
export default {
  name: 'Trademark',
  data() {
    return {
      trademarkList: [], // 品牌列表
      currentPage: 1, // 当前页
      limit: 5, // 每页多少条
      total: 0, // 总条数
      dialogVisible: false, // 遮罩层显示
      imageUrl: '', // 上传图片地址
      tmForm: {
        tmName: '',
        logoUrl: ''
      },
      // 品牌名称校验
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getTrademarkList()
  },
  methods: {
    // 5.修改品牌数据
    async EditTrademark(id) {
      // const {tmName, logoUrl} = trademark
      const res = await reqEditOneTrademark(id)
      console.log(res)
      if (res.code === 200) {
        this.tmForm = res.data
        this.imageUrl = res.data.logoUrl
        this.dialogVisible = true
      }
    },
    // 4.删除一条品牌数据
    async DelOneTrademark(id) {
      this.$confirm('您真的要删除这条数据吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await reqDelOneTrademark(id)
        if (res.code === 200) {
          this.$message.success('删除成功！')
          this.currentPage = this.trademarkList.length === 1 ? this.currentPage - 1 : this.currentPage
          this.getTrademarkList()
        } else {
          this.$message.error('删除失败！')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 3.点击确定按钮添加品牌
    addOrUpdateOneTradeMark() {
      this.$refs['tmForm'].validate(async(valid) => {
        if (valid) {
          let res
          if (this.tmForm.id) {
            res = await reqUpdateOneTrademark(this.tmForm)
          } else {
            res = await reqAddOneTrademark(this.tmForm)
          }
          // console.log(res)
          if (res.code === 200) {
            this.dialogVisible = false
            this.$message.success('操作成功...')
            this.getTrademarkList()
          } else {
            this.$message.err('操作失败...')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 2.点击添加品牌清空对话框并显示遮罩层
    showDialogByAdd() {
      this.imageUrl = ''
      this.tmForm.tmName = ''
      this.tmForm.id = 0
      this.dialogVisible = true
    },
    // 品牌图片上传成功
    handleAvatarSuccess(res, file) {
      // console.log(res, file)
      this.imageUrl = URL.createObjectURL(file.raw)
      this.tmForm.logoUrl = res.data
      // 清除校验规则
      this.$refs['tmForm'].clearValidate(['logoUrl'])
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      const avatarArr = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
      // const isJPG = file.type === 'image/jpeg'
      const isJPG = avatarArr.includes(file.type)
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    },
    // 1.获取品牌信息
    async getTrademarkList() {
      const { currentPage: page, limit } = this
      const res = await reqGetTrademarkList(page, limit)
      if (res.code === 200) {
        this.total = res.data.total
        this.trademarkList = res.data.records
      }
    },
    // 以下两个方法是分页相关
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.limit = val
      this.getTrademarkList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getTrademarkList()
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
